package com.sx.pipeline.ui.needs.operator.add

import android.Manifest
import android.graphics.BitmapFactory
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lxj.xpopup.XPopup
import com.permissionx.guolindev.PermissionX
import com.sx.mvvmlibs.base.EasyAdapter
import com.sx.mvvmlibs.view.SpaceItemDecoration
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.adapter.PushRangeAdapter
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.NeedType
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.CustomCommonPicket
import com.sx.pipeline.custom.dialog.MyCityPickerListener
import com.sx.pipeline.custom.dialog.MyCityPickerPopup
import com.sx.pipeline.databinding.ActOperatorNeedsAddBinding
import com.sx.pipeline.repos.http.res.ProvincesVO
import com.sx.pipeline.ui.needs.operator.NeedsVM
import com.sx.pipeline.utils.AndroidUtil
import com.sx.pipeline.utils.CompressHelper
import com.sx.pipeline.utils.GlideEngine
import com.sx.pipeline.utils.PermissionHelper


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 运营商 发布设备 需求
 */
@Route(path = RoutePath.Mine.OPERATOR_ADD_NEEDS)
class OperatorAddNeedActivity :
    CYDataBindingBaseActivity<ActOperatorNeedsAddBinding, NeedsVM>(R.layout.act_operator_needs_add),
    View.OnClickListener {
    private var mFindMethodAdapter: PushRangeAdapter? = null //查找方式适配器

    private var type: Int = 0 //0是设备查找，1是单位查找，2是服务查找

    private var uploadType = 1 //1现场设备  2现场勘探 3施工图纸
    private var longitude: String = "" //经度
    private var latitude: String = "" //纬度
    private var addressDetail: String = "" //详细地址
    private var startTime: String = "" //开始时间
    private var endTime: String = "" //结束时间


    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        //请求需求类型数据
        mViewModel.getNeed()
        mViewModel.getContacts()
        mViewModel.getUserUnit()
        //联系人默认是本人
        mBinding.etContact.setText(mViewModel.mModel.getUserData()?.userName)
        mBinding.etContactPhone.setText(mViewModel.mModel.getUserData()?.phone)

        //初始化查找方式
        initFindMethod(mViewModel.getFindMethod())

        //初始化现场设备选择
        initMachinePhotos()
        //初始化现场照片
        initExplorationPhotos()
        //初始化施工图纸
        initConstructionDrawings()
    }

    override fun initViewObservable() {
        super.initViewObservable()
        //发起单位名称
        observe(mViewModel.userUnitEvent) {
            mBinding.sbUnitName.rightText = it?.name
        }

        observe(mViewModel.locationEvent) {
//            longitude = it?.latLonPoint?.longitude.toString()
//            latitude = it?.latLonPoint?.latitude.toString()
//            addressDetail = it?.snippet.toString()
            mBinding.etAddressDetail.setText("${it?.title.toString()} ${it?.snippet.toString()}")
        }

        //图片上传结果
        observe(mViewModel.uploadDataEvent) {
            when (uploadType) {
                1 -> mBinding.imageMachinePhotos.addImage(it)
                2 -> mBinding.imageUploadExplorationPhotos.addImage(it)
                3 -> mBinding.imageUploadConstructionDrawings.addImage(it)
            }
        }
    }

    //查找方式
    private fun initFindMethod(data: List<String>) {
        mFindMethodAdapter = PushRangeAdapter(this, data)
        mBinding.rvFindMethod.layoutManager =
            GridLayoutManager(this, 3)
        mBinding.rvFindMethod.addItemDecoration(
            SpaceItemDecoration(15)
        )
        mBinding.rvFindMethod.adapter = mFindMethodAdapter
        mFindMethodAdapter?.selectMode = EasyAdapter.SelectMode.SINGLE_SELECT
        mFindMethodAdapter?.setOnItemSingleSelectListener { itemPosition, isSelected ->

        }
    }


    private fun initMachinePhotos() {
        // 上传图片
        mBinding.imageMachinePhotos.initAdapter(3, 3)
        mBinding.imageMachinePhotos.setImageUploadListener {
            PermissionHelper.requestTip(this,"上次图片需要授权相机和读写权限",object :PermissionUtils.SimpleCallback{
                override fun onGranted() {
                    uploadType = 1
                    PictureSelector.create(this@OperatorAddNeedActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(3 - mBinding.imageMachinePhotos.imagePath.size)
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {
                            override fun onResult(result: ArrayList<LocalMedia?>?) {
                                //循环上传图片
                                for (i in 0 until result?.size!!) {
                                    Log.d("okhttp", "" + result[i]?.realPath)
                                    //压缩图片
                                    val inputBitmap =
                                        BitmapFactory.decodeFile(result[i]?.realPath)
                                    val compressFile = CompressHelper.compressQuality(
                                        this@OperatorAddNeedActivity,
                                        inputBitmap
                                    )
                                    mViewModel.uploadImage(compressFile)
                                }
                            }

                            override fun onCancel() {}
                        })

                }

                override fun onDenied() {
                    ToastUtils.showShort("请授权后再继续操作")
                }
            },Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)

//            PermissionX.init(this)
//                .permissions(
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.CAMERA
//                )
//                .onExplainRequestReason { scope, deniedList ->
//                    scope.showRequestReasonDialog(
//                        deniedList,
//                        "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                        "确认",
//                        "取消"
//                    )
//                }
//                .onForwardToSettings { scope, deniedList ->
//                    scope.showForwardToSettingsDialog(
//                        deniedList,
//                        "您需要手动在“设置”中允许必要的权限",
//                        "确定",
//                        "取消"
//                    )
//                }
//                .request { allGranted, grantedList, deniedList ->
//                    if (allGranted) {
//                        uploadType = 1
//                        PictureSelector.create(this)
//                            .openGallery(SelectMimeType.ofImage())
//                            .setImageEngine(GlideEngine.createGlideEngine())
//                            .setMaxSelectNum(3 - mBinding.imageMachinePhotos.imagePath.size)
//                            .forResult(object : OnResultCallbackListener<LocalMedia?> {
//                                override fun onResult(result: ArrayList<LocalMedia?>?) {
//                                    //循环上传图片
//                                    for (i in 0 until result?.size!!) {
//                                        Log.d("okhttp", "" + result[i]?.realPath)
//                                        //压缩图片
//                                        val inputBitmap =
//                                            BitmapFactory.decodeFile(result[i]?.realPath)
//                                        val compressFile = CompressHelper.compressQuality(
//                                            this@OperatorAddNeedActivity,
//                                            inputBitmap
//                                        )
//                                        mViewModel.uploadImage(compressFile)
//                                    }
//                                }
//
//                                override fun onCancel() {}
//                            })
//                    } else {
//                        ToastUtils.showShort(getString(R.string.txt_these_permissions_are_denied))
//                    }
//                }

        }
    }

    private fun initExplorationPhotos() {
        // 上传图片
        mBinding!!.imageUploadExplorationPhotos.initAdapter(3, 3)
        mBinding!!.imageUploadExplorationPhotos.setImageUploadListener {
            PermissionHelper.requestTip(this,"上次图片需要授权相机和读写权限",object :
                PermissionUtils.SimpleCallback{
                override fun onGranted() {
                    uploadType = 2
                    PictureSelector.create(this@OperatorAddNeedActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(3 - mBinding.imageUploadExplorationPhotos.imagePath.size)
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {
                            override fun onResult(result: ArrayList<LocalMedia?>?) {
                                //循环上传图片
                                for (i in 0 until result?.size!!) {
                                    Log.d("okhttp", "" + result[i]?.realPath)
                                    //压缩图片
                                    val inputBitmap =
                                        BitmapFactory.decodeFile(result[i]?.realPath)
                                    val compressFile = CompressHelper.compressQuality(
                                        this@OperatorAddNeedActivity,
                                        inputBitmap
                                    )
                                    mViewModel.uploadImage(compressFile)
                                }
                            }

                            override fun onCancel() {}
                        })

                }

                override fun onDenied() {
                    ToastUtils.showShort("请授权后再继续操作")
                }
            },Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)

//            PermissionX.init(this)
//                .permissions(
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.CAMERA
//                )
//                .onExplainRequestReason { scope, deniedList ->
//                    scope.showRequestReasonDialog(
//                        deniedList,
//                        "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                        "确认",
//                        "取消"
//                    )
//                }
//                .onForwardToSettings { scope, deniedList ->
//                    scope.showForwardToSettingsDialog(
//                        deniedList,
//                        "您需要手动在“设置”中允许必要的权限",
//                        "确定",
//                        "取消"
//                    )
//                }
//                .request { allGranted, grantedList, deniedList ->
//                    if (allGranted) {
//                        uploadType = 2
//                        PictureSelector.create(this)
//                            .openGallery(SelectMimeType.ofImage())
//                            .setImageEngine(GlideEngine.createGlideEngine())
//                            .setMaxSelectNum(3 - mBinding.imageUploadExplorationPhotos.imagePath.size)
//                            .forResult(object : OnResultCallbackListener<LocalMedia?> {
//                                override fun onResult(result: ArrayList<LocalMedia?>?) {
//                                    //循环上传图片
//                                    for (i in 0 until result?.size!!) {
//                                        Log.d("okhttp", "" + result[i]?.realPath)
//                                        //压缩图片
//                                        val inputBitmap =
//                                            BitmapFactory.decodeFile(result[i]?.realPath)
//                                        val compressFile = CompressHelper.compressQuality(
//                                            this@OperatorAddNeedActivity,
//                                            inputBitmap
//                                        )
//                                        mViewModel.uploadImage(compressFile)
//                                    }
//                                }
//
//                                override fun onCancel() {}
//                            })
//                    } else {
//                        ToastUtils.showShort(getString(R.string.txt_these_permissions_are_denied))
//                    }
//                }

        }
    }

    private fun initConstructionDrawings() {
        // 上传图片
        mBinding!!.imageUploadConstructionDrawings.initAdapter(3, 3)
        mBinding!!.imageUploadConstructionDrawings.setImageUploadListener {
            PermissionHelper.requestTip(this,"上次图片需要授权相机和读写权限",object :
                PermissionUtils.SimpleCallback{
                override fun onGranted() {
                    uploadType = 3
                    PictureSelector.create(this@OperatorAddNeedActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(3 - mBinding.imageUploadConstructionDrawings.imagePath.size)
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {
                            override fun onResult(result: ArrayList<LocalMedia?>?) {
                                //循环上传图片
                                for (i in 0 until result?.size!!) {
                                    Log.d("okhttp", "" + result[i]?.realPath)
                                    //压缩图片
                                    val inputBitmap =
                                        BitmapFactory.decodeFile(result[i]?.realPath)
                                    val compressFile = CompressHelper.compressQuality(
                                        this@OperatorAddNeedActivity,
                                        inputBitmap
                                    )
                                    mViewModel.uploadImage(compressFile)
                                }
                            }

                            override fun onCancel() {}
                        })

                }

                override fun onDenied() {
                    ToastUtils.showShort("请授权后再继续操作")
                }
            },Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)

//            PermissionX.init(this)
//                .permissions(
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.CAMERA
//                )
//                .onExplainRequestReason { scope, deniedList ->
//                    scope.showRequestReasonDialog(
//                        deniedList,
//                        "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                        "确认",
//                        "取消"
//                    )
//                }
//                .onForwardToSettings { scope, deniedList ->
//                    scope.showForwardToSettingsDialog(
//                        deniedList,
//                        "您需要手动在“设置”中允许必要的权限",
//                        "确定",
//                        "取消"
//                    )
//                }
//                .request { allGranted, grantedList, deniedList ->
//                    if (allGranted) {
//                        uploadType = 3
//                        PictureSelector.create(this)
//                            .openGallery(SelectMimeType.ofImage())
//                            .setImageEngine(GlideEngine.createGlideEngine())
//                            .setMaxSelectNum(3 - mBinding.imageUploadConstructionDrawings.imagePath.size)
//                            .forResult(object : OnResultCallbackListener<LocalMedia?> {
//                                override fun onResult(result: ArrayList<LocalMedia?>?) {
//                                    //循环上传图片
//                                    for (i in 0 until result?.size!!) {
//                                        Log.d("okhttp", "" + result[i]?.realPath)
//                                        //压缩图片
//                                        val inputBitmap =
//                                            BitmapFactory.decodeFile(result[i]?.realPath)
//                                        val compressFile = CompressHelper.compressQuality(
//                                            this@OperatorAddNeedActivity,
//                                            inputBitmap
//                                        )
//                                        mViewModel.uploadImage(compressFile)
//                                    }
//                                }
//
//                                override fun onCancel() {}
//                            })
//                    } else {
//                        ToastUtils.showShort(getString(R.string.txt_these_permissions_are_denied))
//                    }
//                }

        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            //选择标题
            R.id.sb_title -> {
                if (mViewModel.needTitleData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_select_request_title))
                popup.setPickerData(mViewModel.needTitleData)
                popup.setCommonPickerListener { _, data ->
                    mBinding.sbTitle.rightText = data
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            //选择需求类型
            R.id.sb_requirement_type -> {
                if (mViewModel.needTypeData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_need_type))
                popup.setPickerData(mViewModel.needTypeData)
                popup.setCommonPickerListener { index, data ->
                    //需求类型
                    type = mViewModel.taskListEvent.value?.TYPE_OF_REQUIREMENT?.get(index)?.type!!
                    mBinding.sbRequirementType.rightText = data
                    mBinding.sbArea.rightText = ""
                    when (mViewModel.taskListEvent.value?.TYPE_OF_REQUIREMENT?.get(index)?.type) {
                        //发布设备需求
                        NeedType.DEVICE_FIND.code -> {
                            mBinding.tabDeviceFind.visibility = View.VISIBLE
                            mBinding.tabFindMethod.visibility = View.VISIBLE
                            mBinding.tabDevicePhoto.visibility = View.VISIBLE

                            mBinding.tabUnitFind.visibility = View.GONE
                            mBinding.tabExplorationPhotos.visibility = View.GONE
                            mBinding.tabConstructionDrawings.visibility = View.GONE
                            mBinding.sbStartTime.visibility = View.GONE
                            mBinding.sbEndTime.visibility = View.GONE
                        }
                        //寻求合作单位需求
                        NeedType.UNIT_FIND.code -> {
                            mBinding.tabDeviceFind.visibility = View.GONE
                            mBinding.tabFindMethod.visibility = View.GONE
                            mBinding.tabDevicePhoto.visibility = View.GONE

                            mBinding.tabUnitFind.visibility = View.VISIBLE
                            mBinding.tabExplorationPhotos.visibility = View.VISIBLE
                            mBinding.tabConstructionDrawings.visibility = View.VISIBLE
                            mBinding.sbStartTime.visibility = View.VISIBLE
                            mBinding.sbEndTime.visibility = View.VISIBLE
                        }
                    }
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            //选择计量单位
            R.id.sb_measurement_unit -> {
                if (mViewModel.needUnitData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup =
                    CustomCommonPicket(this, getString(R.string.txt_choose_measurement_unit))
                popup.setPickerData(mViewModel.needUnitData)
                popup.setCommonPickerListener { _, data ->
                    mBinding.sbMeasurementUnit.rightText = data
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            R.id.sb_area -> {
                //寻求单位合作
                showProvincesDialog()
            }

            R.id.sb_start_time -> {
                CardDatePickerDialog.builder(this)
                    .setTouchHideable(true)
                    .showBackNow(false)
                    .setMinTime(System.currentTimeMillis())
                    .showFocusDateInfo(false)
                    .setWrapSelectorWheel(false)
                    .setTitle("选择开始时间")
                    .showDateLabel(true)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(
                        DateTimeConfig.YEAR,
                        DateTimeConfig.MONTH,
                        DateTimeConfig.DAY,
                        DateTimeConfig.HOUR,
                        DateTimeConfig.MIN
                    )
                    .setLabelText("年", "月")
                    .setOnChoose("选择") {
                        startTime = AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                        mBinding.sbStartTime.rightText =
                            AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                    }
                    .setOnCancel("关闭") {

                    }
                    .build().show()
            }
            R.id.sb_end_time -> {
                CardDatePickerDialog.builder(this)
                    .setTouchHideable(true)
                    .showBackNow(false)
                    .setMinTime(System.currentTimeMillis())
                    .showFocusDateInfo(false)
                    .setWrapSelectorWheel(false)
                    .setTitle("选择结束时间")
                    .showDateLabel(true)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(
                        DateTimeConfig.YEAR,
                        DateTimeConfig.MONTH,
                        DateTimeConfig.DAY,
                        DateTimeConfig.HOUR,
                        DateTimeConfig.MIN
                    )
                    .setLabelText("年", "月")
                    .setOnChoose("选择") {
                        endTime = AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                        mBinding.sbEndTime.rightText =
                            AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                    }
                    .setOnCancel("关闭") {

                    }
                    .build().show()
            }
            //选择详细地址
            R.id.iv_address -> {
                // 手动添加地址
                // 申请权限
                PermissionHelper.requestTip(this,"添加地址需要授权定位权限",object :
                    PermissionUtils.SimpleCallback{
                    override fun onGranted() {
                        RouteManager.Main.intentToSearchLocation()

                    }

                    override fun onDenied() {
                        ToastUtils.showShort("请授权后再继续操作")
                    }
                },Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS)

//                PermissionX.init(this)
//                    .permissions(
//                        Manifest.permission.ACCESS_FINE_LOCATION,
//                        Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
//                    )
//                    .onExplainRequestReason { scope, deniedList ->
//                        scope.showRequestReasonDialog(
//                            deniedList,
//                            "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                            "确认",
//                            "取消"
//                        )
//                    }
//                    .onForwardToSettings { scope, deniedList ->
//                        scope.showForwardToSettingsDialog(
//                            deniedList,
//                            "您需要手动在“设置”中允许必要的权限",
//                            "确定",
//                            "取消"
//                        )
//                    }
//                    .request { allGranted, grantedList, deniedList ->
//                        if (allGranted) {
//                            RouteManager.Main.intentToSearchLocation()
//                        } else {
//                            Toast.makeText(
//                                this,
//                                "这些权限被拒绝,可能影响管建宝正常使用" + ": $deniedList",
//                                Toast.LENGTH_LONG
//                            ).show()
//                        }
//                    }
            }
            R.id.iv_principal -> {
                if (mViewModel.taskContactData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_principal))
                popup.setPickerData(mViewModel.taskContactData)
                popup.setCommonPickerListener { position, data ->
                    mBinding.etContact.setText(data)
                    mBinding.etContactPhone.setText(mViewModel.taskContactPhoneData[position])
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            R.id.tv_commit -> {
                //发布需求
                mViewModel.addNeedOrder(
                    type,
                    mBinding.sbTitle.rightText.toString(),
                    mBinding.etDesc.text.toString(),
                    mBinding.sbRequirementType.rightText.toString(),
                    mBinding.etDeviceName.text.toString(),
                    mBinding.etProductNumber.text.toString(),
                    mBinding.etProductNumber.text.toString(),
                    AndroidUtil.listToString(mBinding.imageMachinePhotos.imagePath).toString(),
                    mFindMethodAdapter!!.singleSelectedPosition,
                    mBinding.sbArea.rightText.toString(),
                    mBinding.etAddressDetail.text.toString(),
                    mBinding.etContact.text.toString(),
                    mBinding.etContactPhone.text.toString(),
                    mBinding.etWorkload.text.toString(),
                    mBinding.sbMeasurementUnit.rightText.toString(),
                    startTime,
                    endTime,
                    0,
                    AndroidUtil.listToString(mBinding.imageUploadExplorationPhotos.imagePath)
                        .toString(),
                    AndroidUtil.listToString(mBinding.imageUploadConstructionDrawings.imagePath)
                        .toString(),
                )
            }
        }
    }


    /**
     * 省市区选择
     */
    private fun showProvincesDialog() {
        val popup = MyCityPickerPopup(ActivityUtils.getTopActivity())
        popup.setCityPickerListener(object : MyCityPickerListener {
            override fun onCityConfirm(
                provincesVO: ProvincesVO?, cityVO: ProvincesVO?, areaVO: ProvincesVO?,
                province: String?, city: String?, area: String?, v: View?,
            ) {
                mViewModel.provinceIDField.set(provincesVO!!.id.toInt())
                mViewModel.cityIDField.set(cityVO!!.id.toInt())
                mViewModel.areaIDField.set(areaVO!!.id.toInt())
                Log.d(
                    "fdsafa",
                    "省level=${provincesVO.level}市level=${cityVO.level}区level=${areaVO.level}"
                )
                mViewModel.addressField.set("$province $city $area")
                mViewModel.longitudeField.set(areaVO.center.split(",")[0])
                mViewModel.latitudeField.set(areaVO.center.split(",")[1])
                // 显示地址
                mBinding.sbArea.rightText = "$province $city $area"
            }

            override fun onCityChange(province: String?, city: String?, area: String?) {

            }
        })
        XPopup.Builder(this).asCustom(popup).show()
    }
}